/**
 * This file is part of Wasagent.
 *
 * Wasagent is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Wasagent is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Wasagent. If not, see <http://www.gnu.org/licenses/>.
 * 
 * HandleSocket.java : Handles the requests to the server, gets the 
 *                     connections, and writes the reply to the client.
 */


import net.wait4it.wasagent.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.io.*;
import java.util.Map;
import java.util.HashMap;

class HandleSocket  extends Thread implements Runnable
{
    private String                       reqmsg = "";
    private Socket                       socket;
    private DataOutputStream             output;
    private BufferedReader               input;
    private ArrayList<WasModule>         modules;
    private FileWriter                   logfile;

    // WasModule
    //private WasModule                    module;

    public HandleSocket(Socket socket, ArrayList<WasModule> modules) {
        this.socket = socket;
        this.modules = modules;
    }

    public void run() {
        try {

            String tmpmsg;
            String outputmsg;
            boolean exit = false;
            int contentlength=0;
            int contentreaded=0;
                
            input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            output = new DataOutputStream(socket.getOutputStream());

            int   reqc;

            // GET the HTTP request from socket
            // 2do: Parse correctly the GET request
            while(!exit) {
                tmpmsg = input.readLine();
                if(tmpmsg.equals("")) {
                    exit = true;
                }
                else if(tmpmsg.startsWith("POST"));
                else if(tmpmsg.startsWith("GET"))
                {
                    reqmsg = tmpmsg.split(" ")[1];
                }
                else if(tmpmsg.startsWith("Content-Length:")) {
                    contentlength=Integer.parseInt(tmpmsg.substring(tmpmsg.indexOf(":")+1,tmpmsg.length()).trim());
                }
            }

            while( contentlength>contentreaded && (reqc = input.read()) != -1) {
                reqmsg+= (char) reqc;
                contentreaded++;
            }

            //
            // Parse the request params
            //
          
            Map<String,String> params = new HashMap<String,String>();
            String[] reqparameters = reqmsg.split("&");
            for(int i=0; i<reqparameters.length; i++)
            {
                String[] reqparam = reqparameters[i].split("=");
                params.put(reqparam[0],reqparam[1]);
                //System.out.println("Put-params [" + i + "]:" + reqparam[0] + "=>" + reqparam[1]);
            }

            // 
            // Iterate through existing WasModules searching for existing connections to server
            //
            
            WasModule module=null;
            String wasModuleIdbyHostnamePort = params.get("hostname") + ":" + params.get("port");

            for(int i=0; i< modules.size() && module == null; i++ )
                if(modules.get(i).isThis(wasModuleIdbyHostnamePort))
                    module=modules.get(i);

            if(module==null)
            {
                module=new WasModule();
                modules.add(module);
            }


            outputmsg = module.run(params);
            
            output.writeBytes("HTTP/1.1 200 Found\n");
            output.writeBytes("Server: WasAgent2\n");
            output.writeBytes("Content-Length: "+ outputmsg.length()+"\n\n");

            output.writeBytes(outputmsg+"\n");
            output.flush();
            socket.close();
            
        }
        catch(Exception e) {
            System.out.println("Error: "+ e.toString());          
        }
          
     }

}
